/**
 * Copyright (c) 2018 苍穹跃龙
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.l.core.mybatis;

import java.util.Date;

import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.l.core.util.WebUtils;
import com.l.web.master.system.entity.SysUser;

/**
 * @author 严秋旺
 * @date 2018-10-03
 */
public class BaseMetaObjectHandler extends MetaObjectHandler {
    private static final String FIELD_CREATE_BY = "createBy";
    private static final String FIELD_CREATE_TIME = "createTime";
    private static final String FIELD_DEL = "del";

    private static final String FIELD_UPDATE_BY = "updateBy";
    private static final String FIELD_UPDATE_TIME = "updateTime";
    
    private GlobalConfiguration globalConfig;

    public BaseMetaObjectHandler(GlobalConfiguration globalConfig) {
        this.globalConfig = globalConfig;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        Object createBy = getFieldValByName(FIELD_CREATE_BY, metaObject);
        
        if (createBy == null) {
            SysUser login = WebUtils.getLogin();

            if (login != null) {
                setFieldValByName(FIELD_CREATE_BY, login.getId(), metaObject);
            }
        }

        Object createDate = getFieldValByName(FIELD_CREATE_TIME, metaObject);

        if (createDate == null) {
            setFieldValByName(FIELD_CREATE_TIME, new Date(), metaObject);
        }
        
        Object del = getFieldValByName(FIELD_DEL, metaObject);

        if (del == null) {
            setFieldValByName(FIELD_DEL, globalConfig.getLogicNotDeleteValue(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateBy = getFieldValByName(FIELD_UPDATE_BY, metaObject);
        
        if (updateBy == null) {
            SysUser login = WebUtils.getLogin();

            if (login != null) {
                setFieldValByName(FIELD_UPDATE_BY, login.getId(), metaObject);
            }
        }

        Object updateDate = getFieldValByName(FIELD_UPDATE_TIME, metaObject);

        if (updateDate == null) {
            setFieldValByName(FIELD_UPDATE_TIME, new Date(), metaObject);
        }
    }

}
